/**
 * @author zhouheng
 * @date 2022年03月03日 17:23
 */

package com.atguigu.gulimall.product.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("index/testRedis")
    public String testRedis() {
        return "";
    }

    @GetMapping({"/",  "index.html"})
    public String getIndex(Model model) {
        //获取所有的一级分类
        List<CategoryEntity> catagories = categoryService.getLevel1Catagories();
        model.addAttribute("catagories", catagories);

        return "index";
    }

    @GetMapping("/testUpdateCacheEvit")
    @ResponseBody
    public String testUpdateCacheEvit(Model model) {
        categoryService.testCachEvit();

        return "success";
    }

    /*
     * @author zhouheng
     * 一级分类
     * @date 2022/3/3 0003 18:43
     * @param null
     * @return null
     */
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> caltelogJson() {
        Map<String, List<Catelog2Vo>> categoriesDb = categoryService.getCatelogJson();
        return categoriesDb;
    }

    /**
     * RLock锁有看门狗机制 会自动帮我们续期，默认三秒自动过期
     * lock.lock(10,TimeUnit.SECONDS); 十二猴子的时间一定要大于业务的时间 否则会出现死锁的情况
     * <p>
     * 如果我们传递了锁的超时时间就给redis发送超时脚本 默认超时时间就是我们指定的
     * 如果我们未指定，就使用 30 * 1000 [LockWatchdogTimeout]
     * 只要占锁成功 就会启动一个定时任务 任务就是重新给锁设置过期时间 这个时间还是 [LockWatchdogTimeout] 的时间 1/3 看门狗的时间续期一次 续成满时间
     */
    @ResponseBody
    @RequestMapping("/index/hello")
    public String hello() {
        RLock lock = redissonClient.getLock("my-lock");
        // 阻塞式等待
        lock.lock();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return "hello";
    }

    @RequestMapping("/redisson")
    @ResponseBody
    public String testRedisson(){
        //获取分布式锁，只要锁的名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("lock");

        //加锁（阻塞等待），默认过期时间是30秒
        lock.lock();
        try{
            //如果业务执行过长，Redisson会自动给锁续期
            Thread.sleep(1000);
            System.out.println(lock.getName());
            System.out.println("加锁成功，执行业务逻辑");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //解锁，如果业务执行完成，就不会继续续期，即使没有手动释放锁，在30秒过后，也会释放锁
            lock.unlock();
        }

        return "Hello Redisson!";
    }

    @GetMapping("/index/write")
    @ResponseBody
    public void writeValue() {
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        RLock wLock = lock.writeLock();
        wLock.lock();
        try {
           stringRedisTemplate.opsForValue().set("writeValue", "1111");
           Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            wLock.unlock();
        }
    }


    @GetMapping("/index/read")
    @ResponseBody
    public String readValue() {
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = lock.readLock();
        String s = "";
        rLock.lock();
        try {
            System.out.println(rLock.getName() + "开始读。。。。");
            System.out.println(new Date());
            s = stringRedisTemplate.opsForValue().get("writeValue");
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
        return s;
    }

    @GetMapping("index/lockDoor")
    @ResponseBody
    public R lockDoor() throws InterruptedException {
        System.out.println("筒子们赶紧离开拉，我准备锁门了");
        RCountDownLatch door_lock = redissonClient.getCountDownLatch("door_lock");
        door_lock.trySetCount(5);
        door_lock.await();

        return R.ok().put("data", "好的，人走光了，开始锁门");
    }

    @GetMapping("index/gogogo/{studentId}")
    @ResponseBody
    public void lockDoor(@PathVariable("studentId") Long studentId) throws InterruptedException {
        System.out.println("第"+studentId+"个同学离开了");
        RCountDownLatch door_lock = redissonClient.getCountDownLatch("door_lock");
        door_lock.countDown();
        System.out.println("剩余"+door_lock.getCount()+"个同学没走");
    }
}
